package listbyorder.access001_100.test95;

import listbyorder.utils.TreeNode;

import java.util.ArrayList;
import java.util.List;

/**
 * @author code_yc
 * @version 1.0
 * @date 2020/6/6 9:33
 */
public class Solution1 {

    public List<TreeNode> generateTrees(int n) {
        if (n == 0) return new ArrayList<TreeNode>();
        return getAns(1, n);
    }

    private List<TreeNode> getAns(int s, int e) {
        List<TreeNode> ans = new ArrayList<TreeNode>();
        if (s > e) {
            ans.add(null);
            return ans;
        }
        if (s == e) {
            ans.add(new TreeNode(s));
            return ans;
        }
        for (int r = s; r <= e; r++) {
            // 从s到e轮流作为根节点
            List<TreeNode> left = getAns(s, r - 1);
            List<TreeNode> right = getAns(r + 1, e);
            for (TreeNode rt : right) {
                for (TreeNode lt : left) {
                    TreeNode root = new TreeNode(r);
                    root.left = lt;
                    root.right = rt;
                    ans.add(root);
                }
            }
        }
        return ans;
    }
}
